package xx.iverson.util;


import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;

import java.awt.*;
import java.awt.image.BufferedImage;
import java.util.Random;

/**
 * xx.iverson.util.CaptchaUtil
 * 描述：验证码工具类
 * on 2025/6/18-下午3:25
 *
 * @author weijx
 */
public class CaptchaUtil {
    private static final int WIDTH = 120;
    private static final int HEIGHT = 40;
    private static final int CODE_LENGTH = 4;
    private static final String[] FONT_NAMES = {"Arial", "Courier", "Verdana", "Tahoma"};
    private static final Random RANDOM = new Random();
    private static final String CAPTCHA_SESSION_KEY = "captcha";

    public static BufferedImage generateCaptchaImage(HttpServletRequest request) {
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics2D g = image.createGraphics();

        // 设置背景色
        g.setColor(getRandomColor(200, 250));
        g.fillRect(0, 0, WIDTH, HEIGHT);

        // 绘制干扰线
        g.setColor(getRandomColor(160, 200));
        for (int i = 0; i < 20; i++) {
            int x1 = RANDOM.nextInt(WIDTH);
            int y1 = RANDOM.nextInt(HEIGHT);
            int x2 = RANDOM.nextInt(WIDTH);
            int y2 = RANDOM.nextInt(HEIGHT);
            g.drawLine(x1, y1, x2, y2);
        }

        // 生成验证码
        StringBuilder captchaCode = new StringBuilder();
        for (int i = 0; i < CODE_LENGTH; i++) {
            String ch = String.valueOf(RANDOM.nextInt(10));
            captchaCode.append(ch);

            // 设置字体
            g.setFont(new Font(
                    FONT_NAMES[RANDOM.nextInt(FONT_NAMES.length)],
                    Font.BOLD,
                    25 + RANDOM.nextInt(5)
            ));

            // 绘制字符
            g.setColor(getRandomColor(20, 130));
            g.drawString(ch, 20 + i * 25, 30);
        }

        // 保存验证码到session
        HttpSession session = request.getSession();
        session.setAttribute(CAPTCHA_SESSION_KEY, captchaCode.toString());

        // 添加噪点
        float yawpRate = 0.05f;
        int area = (int) (yawpRate * WIDTH * HEIGHT);
        for (int i = 0; i < area; i++) {
            int x = RANDOM.nextInt(WIDTH);
            int y = RANDOM.nextInt(HEIGHT);
            image.setRGB(x, y, getRandomColor(100, 255).getRGB());
        }

        // 扭曲图片
        shear(g, getRandomColor(200, 250));

        g.dispose();
        return image;
    }

    public static boolean validateCaptcha(HttpServletRequest request, String inputCode) {
        if (inputCode == null || inputCode.isEmpty()) {
            return false;
        }

        HttpSession session = request.getSession();
        String captcha = (String) session.getAttribute(CAPTCHA_SESSION_KEY);
        session.removeAttribute(CAPTCHA_SESSION_KEY);

        return inputCode.equalsIgnoreCase(captcha);
    }

    private static Color getRandomColor(int fc, int bc) {
        if (fc > 255) {
            fc = 255;
        }
        if (bc > 255) {
            bc = 255;
        }
        int r = fc + RANDOM.nextInt(bc - fc);
        int g = fc + RANDOM.nextInt(bc - fc);
        int b = fc + RANDOM.nextInt(bc - fc);
        return new Color(r, g, b);
    }

    private static void shear(Graphics g, Color color) {
        shearX(g, color);
        shearY(g, color);
    }

    private static void shearX(Graphics g, Color color) {
        int period = RANDOM.nextInt(2);
        int frames = 1;
        int phase = RANDOM.nextInt(2);

        for (int i = 0; i < CaptchaUtil.HEIGHT; i++) {
            double d = (double) (0)
                    * Math.sin((double) i / (double) period
                    + (6.2831853071795862D * (double) phase) / (double) frames);
            g.copyArea(0, i, CaptchaUtil.WIDTH, 1, (int) d, 0);
            g.setColor(color);
            g.drawLine((int) d, i, 0, i);
            g.drawLine((int) d + CaptchaUtil.WIDTH, i, CaptchaUtil.WIDTH, i);
        }
    }

    private static void shearY(Graphics g, Color color) {
        int period = RANDOM.nextInt(40) + 10;
        int frames = 20;
        int phase = 7;
        for (int i = 0; i < CaptchaUtil.WIDTH; i++) {
            double d = (double) (period >> 1)
                    * Math.sin((double) i / (double) period
                    + (6.2831853071795862D * (double) phase) / (double) frames);
            g.copyArea(i, 0, 1, CaptchaUtil.HEIGHT, 0, (int) d);
            g.setColor(color);
            g.drawLine(i, (int) d, i, 0);
            g.drawLine(i, (int) d + CaptchaUtil.HEIGHT, i, CaptchaUtil.HEIGHT);
        }
    }
}
